import * as cc from "cc";
import yyComponent from "../Common/yyComponent";
import GlobalPool from "../Common/GlobalPool";
import { GlobalEnum } from "../GameSpecial/GlobalEnum";
import { EventType } from "../GameSpecial/GameEventType";

//互推游戏节点容器
const { ccclass, property } = cc._decorator;

@ccclass
export default class RecommendContainer extends yyComponent {

    @property(cc.Node)
    protected content: cc.Node = null;    //存放互推节点的父节点
    protected contentTransform: cc.UITransform = null;
    protected contentParentTransform: cc.UITransform = null;
    protected initContentTransform() {
        this.contentTransform = this.content.getComponent(cc.UITransform);
        this.contentParentTransform = this.content.parent.getComponent(cc.UITransform);
    }
    @property({
        tooltip: "容器中要显示的广告位数量，0表示显示全部内容"
    })
    public count: number = 0;
    protected data: any;//互推数据，包含容器节点的布局，互推节点类型，互推游戏数据等
    /**暂停滚动的剩余时间(点击广告位时，暂停滚动所有广告位) */
    protected pauseTime: number = 0;
    /**暂停滚动广告位内容 */
    protected pauseUpdateContent() {
        this.pauseTime = 5;
    }

    public init(data?: any) {
        this.onEvents();
        if (!!data) {
            this.setData(data);
        }
    }
    protected onEvents() {
        this.on(EventType.Common.RecommendEvent.clickRecommendItem, this.pauseUpdateContent, this);
    }
    public reset() {
        this.resetItems();
    }
    protected resetItems() {
        GlobalPool.putAllChildren(this.content);
    }
    public reuse(data: any) {
        this.reset();
        this.setData(data);
    }

    public unuse() {
        this.reset();
    }


    public show(d?) {
        super.show(d);
        this.pauseTime = 0;
    }

    public hide() {
        this.reset();
        this.node.active = false;
    }

    /**设置互推游戏内容 */
    public setRecommendData(items: any[]) {
        if (this.node.activeInHierarchy && this.content.children.length == 0) {
            this.data.items = items;
            this.addItems(items, this.data.itemType);
            this.content.getComponent(cc.Layout).updateLayout();
            this.content.setPosition(0, 0);
            let scr = this.content.parent.parent.getComponent(cc.ScrollView);
            if (!!scr) {
                scr.scrollTo(cc.v2(0, 0), 0);
            }
        }
    }
    /**刷新互推内容，随机排序后再显示 */
    public refreshRecommendData() {
        if (!this.node.activeInHierarchy) return;

        let nodes = [].concat(this.content.children);
        this.content.removeAllChildren();
        for (let i = nodes.length - 1; i >= 0; --i) {
            let index = Math.round(Math.random() * (nodes.length - 1));
            this.content.addChild(nodes[index]);
            nodes.splice(index, 1);
        }

    }

    /**延迟显示误触按钮 */
    protected delayShowBannerToucher(btn, data) {
        if (!btn) return;
        if (!data) {
            btn.node.active = true;
            btn.show();
            return;
        }
        let config = data.config;
        if (!!config && !!config[GlobalEnum.Common.RecommendFlowConfig.recommendBtnShowDelay]) {
            btn.node.active = false;
            setTimeout(() => {
                btn.node.active = true;
                btn.show(config);
            }, config[GlobalEnum.Common.RecommendFlowConfig.recommendBtnShowDelay] * 1000);
        } else {
            btn.node.active = true;
            btn.show(config);
        }
    }
    /**延迟显示按钮 */
    protected delayShowNode(node, data) {
        if (!node) return;
        if (!data) {
            node.active = true;
            return;
        }
        let config = data.config;
        if (!!config && !!config[GlobalEnum.Common.RecommendFlowConfig.recommendBtnShowDelay]) {
            node.active = false;
            setTimeout(() => {
                node.active = true;
            }, config[GlobalEnum.Common.RecommendFlowConfig.recommendBtnShowDelay] * 1000);
        } else {
            node.active = true;
        }
    }


    /**自动随机跳转当前广告位中的游戏 */
    protected autoRandomJump() {
        if (!this.data || !this.data.items || this.data.items.length <= 0) {
            return;
        }
        let index = Math.floor(Math.random() * (this.data.items.length - 0.00001));
        let data = this.data.items[index];
        this.emit(EventType.Common.RecommendEvent.autoNavigate, data);
    }

    /**设置节点布局 */
    public setWidgetConfig(data: { scale?: number, pos?: cc.Vec2, widget?: any }) {
        if (!this.data) {
            this.data = {};
        }
        if (undefined !== data.scale) {
            this.data.scale = data.scale;
        }
        if (undefined !== data.pos) {
            this.data.pos = data.pos;
        }
        if (undefined !== data.widget) {
            this.data.widget = data.widget;
        }
        this.setWidget(this.node.children[0], this.data.widget, cc.find("Canvas/Recommend"));
    }

    protected setData(data: any) {
        this.data = data;
        this.setNodeWidget();
        if (!!data.items && data.items.length > 0) {
            let items = data.items;
            this.addItems(items, data.itemType);
            this.content.getComponent(cc.Layout).updateLayout();
            this.content.setPosition(0, 0);
            let scr = this.content.parent.parent.getComponent(cc.ScrollView);
            if (!!scr) {
                scr.scrollTo(cc.v2(0, 0), 0);
            }
        }
    }
    /**根据容器布局属性设置容器大小、坐标 */
    protected setNodeWidget() {
        if (undefined !== this.data.scale) {
            this.node.setScale(this.data.scale);
        }
        if (undefined !== this.data.pos) {
            this.node.setPosition(this.data.pos);
        }
        if (undefined !== this.data.widget) {
            this.setWidget(this.node.children[0], this.data.widget, cc.find("Canvas/Recommend"));
        }
    }

    //添加互推游戏节点
    protected addItems(data: any[], type) {
        let count = this.count;
        if (count <= 0 || count > data.length) {
            count = data.length;
        }
        let prefabName = "RecommendItem_" + type;
        for (let i = 0; i < count; ++i) {
            let item = this.getItem(prefabName, data[i]);
            this.content.addChild(item);
        }
    }
    /**根据类型获取对应的预制件 */
    protected getItem(prefabName, data: any) {
        return GlobalPool.get(prefabName, data);
    }

    //设置布局组件
    protected setWidget(node: cc.Node, widget: any, targetNode?: cc.Node) {
        //尺寸
        let trans = node.getComponent(cc.UITransform);
        if (undefined !== widget.width) {
            trans.width = widget.width;
        }
        if (undefined !== widget.height) {
            trans.height = widget.height;
        }
        let p = cc.v3();
        let dirty: boolean = false;
        if (undefined !== widget.x) {
            p.x = widget.x;
            dirty = true;
        } else {
            p.x = node.position.x;
        }
        if (undefined !== widget.y) {
            p.y = widget.y;
            dirty = true;
        } else {
            p.y = node.position.y;
        }
        if (dirty) {
            p.z = node.position.z;
            node.setPosition(p);
        }

        //缩放
        p.x = p.y = p.z = 1;
        if (undefined !== widget.scale) {
            p.x = widget.scale.x;
            p.y = widget.scale.y;
        }
        node.setScale(p);

        let wg = node.getComponent(cc.Widget);
        if (!wg) {
            wg = node.addComponent(cc.Widget);
        }
        wg.isAbsoluteBottom = true;
        wg.isAbsoluteLeft = true;
        wg.isAbsoluteRight = true;
        wg.isAbsoluteTop = true;
        wg.isAbsoluteHorizontalCenter = true;
        wg.isAbsoluteVerticalCenter = true;
        if (!widget) return;
        if (!!targetNode) {
            wg.target = targetNode;
        } else {
            wg.target = node.parent;
        }
        //上
        if (undefined !== widget.top) {
            wg.isAlignTop = true;
            wg.isAbsoluteTop = widget.top > 1;
            wg.top = parseFloat(widget.top);
        } else {
            wg.isAlignTop = false;
        }
        //下
        if (undefined !== widget.bottom) {
            wg.isAlignBottom = true;
            wg.isAbsoluteBottom = widget.bottom > 1;
            wg.bottom = parseFloat(widget.bottom);
        } else {
            wg.isAlignBottom = false;
        }
        //左
        if (undefined !== widget.left) {
            wg.isAlignLeft = true;
            wg.isAbsoluteLeft = widget.left > 1;
            wg.left = parseFloat(widget.left);
        } else {
            wg.isAlignLeft = false;
        }
        //右
        if (undefined !== widget.right) {
            wg.isAlignRight = true;
            wg.isAbsoluteRight = widget.right > 1;
            wg.right = parseFloat(widget.right);
        } else {
            wg.isAlignRight = false;
        }

        wg.isAlignHorizontalCenter = !!widget.horizontalCenter;
        wg.isAlignVerticalCenter = !!widget.verticalCenter;
        this.updateWidget(node);
    }
    protected updateWidget(node: cc.Node) {
        let wg = node.getComponent(cc.Widget);
        if (!!wg) {
            wg.updateAlignment();
        }
        for (let i = node.children.length - 1; i >= 0; --i) {
            this.updateWidget(node.children[i]);
        }
    }

    /***********************************************************滚动功能***********************************************************/
    /**滚动速度，像素/秒 */
    protected recommendMoveSpd: number = 50;
    //#region 水平滚动
    protected moveLeft: boolean = true;
    protected updateRecommendH(dt: number) {
        if (this.pauseTime > 0) {
            this.pauseTime -= dt;
            return;
        }
        if (this.contentTransform.width <= this.contentParentTransform.width) {
            return;
        }

        let x;
        if (this.moveLeft) {
            x = this.content.position.x - dt * this.recommendMoveSpd;
            if (x + this.contentTransform.width <= this.contentParentTransform.width) {
                x = this.contentParentTransform.width - this.contentTransform.width;
                this.moveLeft = false;
            }
        } else {
            x = this.content.position.x + dt * this.recommendMoveSpd;
            if (x >= 0) {
                x = 0;
                this.moveLeft = true;
            }
        }
        this.content.setPosition(x, 0);
    }
    //#endregion

    //#region 垂直滚动
    protected moveUp: boolean = true;
    protected updateRecommendV(dt: number) {
        if (this.pauseTime > 0) {
            this.pauseTime -= dt;
            return;
        }
        if (this.contentTransform.height <= this.contentParentTransform.height) {
            return;
        }

        let y;
        if (this.moveUp) {
            y = this.content.position.y + dt * this.recommendMoveSpd;
            if (y - this.contentTransform.height + this.contentParentTransform.height >= 0) {
                y = this.contentTransform.height - this.contentParentTransform.height;
                this.moveUp = false;
            }
        } else {
            y = this.content.position.y - dt * this.recommendMoveSpd;
            if (y <= 0) {
                y = 0;
                this.moveUp = true;
            }
        }
        this.content.setPosition(0, y);
    }
    //#endregion

}
